package com.toman.ui.work;


import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.device.ScanManager;
import android.device.scanner.configuration.PropertyID;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.githang.statusbar.StatusBarCompat;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.SysMenuEntityNew;
import com.toman.MyApplication;
import com.toman.R;
import com.toman.Util.CProgressDialogUtils;
import com.toman.Util.IntentUtils;
import com.toman.Util.JsonExcludeNull;
import com.toman.Util.JsonUtils;
import com.toman.Util.NetworkUtils;
import com.toman.Util.PermissonUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.StringUtils;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.ui.menu.MenuJump;
import com.toman.ui.menu.MenuManageActivity;
import com.toman.ui.menu.adapter.IndexDataAdapter;
import com.toman.ui.msg.MsgUnReadActivity;
import com.toman.ui.my.FeedBackActivity;
import com.toman.ui.work.base.BeltlineInfActivity;
import com.toman.ui.work.base.TerminalInfActivity;
import com.toman.ui.work.base.UserInfActivity;
import com.toman.ui.work.management.ProblemFeedbackActivity;
import com.toman.ui.work.scan.ScanDeviceEmptyActivity;
import com.toman.update.UpdateAppHttpUtil;
import com.toman.widget.CustomCaptureActivity;
import com.toman.widget.MyGridView;
import com.umeng.analytics.MobclickAgent;

import com.umeng.commonsdk.statistics.SdkVersion;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;
import com.vector.update_app.listener.ExceptionHandler;
import com.vector.update_app.listener.IUpdateDialogFragmentListener;
import com.vector.update_app.utils.AppUpdateUtils;
import com.ywanhzy.demo.AppConfig;
import com.ywanhzy.demo.AppContext;
import com.ywanhzy.demo.entity.MenuEntity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import androidkun.com.versionupdatelibrary.entity.VersionUpdateConfig;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import okhttp3.Request;
import okhttp3.Response;

import static android.app.Activity.RESULT_OK;
import static com.toman.Interfaces.NewBaseUrl.SCANNING_CODE;


/**
 * A simple {@link Fragment} subclass.
 */
public class WorkFragment extends Fragment {
    String contents;
    String version;
    String attachfile;
    //     0普通更新   1强制更新
    String mustUpdate = "0";
    Unbinder unbinder;
//扫码相关
    private Vibrator mVibrator;
    private ScanManager mScanManager;
    private SoundPool soundpool = null;
    private int soundid;
    private String barcodeStr;


    Unbinder unbinder1;
    private static AppContext appContext;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_scan)
    ImageView ivScan;
    @BindView(R.id.ll_scan)
    LinearLayout llScan;
    @BindView(R.id.cv_work)
    CardView cvWork;
    @BindView(R.id.tv_work_count)
    TextView tvWorkCount;
    private IndexDataAdapter adapter;
    private List<MenuEntity> indexDataList = new ArrayList<>();
    private ArrayList<MenuEntity> indexAll = new ArrayList<>();
    @BindView(R.id.bga_refresh)
    BGARefreshLayout bgaRefresh;
    @BindView(R.id.gv_lanuch_start)
    MyGridView gridView;
    private final static String SCAN_ACTION = ScanManager.ACTION_DECODE;//default action

    public WorkFragment() {
        // Required empty public constructor
    }

    public MyApplication myApplication;

    View rootView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rootView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_work,
                null);

        unbinder = ButterKnife.bind(this, rootView);
        getAll();
        initView();
        appUpdata();


//        updateDiy();
//        newYearDialog();
//        ViewUtil.lagout(401,getActivity());
//        test();
    }

    private void initView() {
        appContext = (AppContext) getActivity().getApplication();
        mVibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);

        gridView.setFocusable(true);
        adapter = new IndexDataAdapter(getActivity(), indexDataList);
        gridView.setAdapter(adapter);
        if (!NewBaseUrl.base.equals("https://www.zjtmcloud.com/proxyApi")){
            tvTitle.setText("工作台（"+NewBaseUrl.base+"）");
        }
//        getSelect();
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                Bundle bundle = new Bundle();

                String title = indexDataList.get(position).getTitle();
                String strId = indexDataList.get(position).getId();
                if (strId.equals("all")) {// 更多
                    intent.setClass(getActivity(), MenuManageActivity.class);
                    startActivity(intent);
                } else {
                    logSave(strId);
                    MenuJump.go(getActivity(), title);
                }

            }
        });

        bgaRefresh.setRefreshViewHolder(new BGANormalRefreshViewHolder(MyApplication.getInstance(), false));

        bgaRefresh.setDelegate(new BGARefreshLayout.BGARefreshLayoutDelegate() {
            @Override
            public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
                if (NetworkUtils.checkNetState(getActivity())) {
                    // 如果网络可用，则加载网络数据
                    getSelect();

                } else {
                    // 网络不可用，结束下拉刷新
                    bgaRefresh.endRefreshing();
                }
            }

            @Override
            public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
                return false;
            }
        });
    }
    private void initScan() {
        // TODO Auto-generated method stub
        try {
            mScanManager = new ScanManager();
            mScanManager.openScanner();
            mScanManager.switchOutputMode( 0);
            soundpool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100); // MODE_RINGTONE
            soundid = soundpool.load("/etc/Scan_new.ogg", 1);
        } catch (Exception e) {
//            e.printStackTrace();
        }
    }
    public void getAll() {

        OkHttpUtils
                .get(NewBaseUrl.company_customusermenu_all_List)
                .params("token", (String) SPUtils.get(getActivity(), "token", ""))
                .params("userId", (String) SPUtils.get(getActivity(), "userid", ""))
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "选择的项目: " + result);

                        com.alibaba.fastjson.JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getActivity());


                        if (code == 0) {
                            indexAll.clear();
                            PermissonUtils.clear(getActivity());
                            List<SysMenuEntityNew> menuList = new ArrayList<SysMenuEntityNew>(JsonExcludeNull.parseArrayExcludeNull(jsonObj.getString("sysEmployeeMenuList"), SysMenuEntityNew.class));

                            for (SysMenuEntityNew entityNew : menuList) {

                                MenuEntity menuEntity = new MenuEntity();
                                menuEntity.setTitle(entityNew.getName());
                                menuEntity.setId(entityNew.getMenuId());
                                menuEntity.setChilds(new ArrayList<>());
                                for (SysMenuEntityNew entityChild : entityNew.getList()) {
                                    MenuEntity childEntity = new MenuEntity();
                                    childEntity.setTitle(entityChild.getName());
                                    childEntity.setIco(entityChild.getAppIconUrl());
                                    childEntity.setId(entityChild.getMenuId());
                                    try {
                                        for (SysMenuEntityNew sysMenuEntityPer : entityChild.getList()) {
                                            PermissonUtils.put(getActivity(), entityChild.getName() + sysMenuEntityPer.getName(), "是");
                                            ToastUtil.print(entityChild.getName() + sysMenuEntityPer.getName() + ";");
                                        }

                                        if (StringUtils.isNotEmpty(entityChild.getIsUse())) {
                                            if (entityChild.getIsUse().equals("1")) {
                                                childEntity.setSelect(true);
                                            }
                                        }


                                        menuEntity.getChilds().add(childEntity);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }

                                indexAll.add(menuEntity);
                            }
                            appContext.saveObject((Serializable) indexAll, AppConfig.KEY_All);


                        } else {
                            ToastUtil.makeText(getActivity(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    public void getSelect() {
        OkHttpUtils
                .get(NewBaseUrl.company_customusermenu_list)
                .params("token", (String) SPUtils.get(getActivity(), "token", ""))
                .params("userId", (String) SPUtils.get(getActivity(), "userid", ""))
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "选择的项目: " + result);

                        com.alibaba.fastjson.JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getActivity());
                        if (bgaRefresh!=null){
                            bgaRefresh.endRefreshing();
                        }
                        if (code == 0) {
                            List<SysMenuEntityNew> menuList = new ArrayList<SysMenuEntityNew>(JsonExcludeNull.parseArrayExcludeNull(jsonObj.getString("menuList"), SysMenuEntityNew.class));
//                            indexDataList=new ArrayList<>();
                            indexDataList.clear();

                            for (SysMenuEntityNew entityNew : menuList) {
                                MenuEntity menuEntity = new MenuEntity();
                                menuEntity.setTitle(entityNew.getName());
                                menuEntity.setIco(entityNew.getAppIconUrl());
                                menuEntity.setId(entityNew.getMenuId());
                                if (StringUtils.isNotEmpty(entityNew.getIsUse())) {
                                    if (entityNew.getIsUse().equals("1")) {
                                        menuEntity.setSelect(true);
                                    }
                                }

                                indexDataList.add(menuEntity);
                            }
                            appContext.saveObject((Serializable) indexDataList, AppConfig.KEY_USER);
                            MenuEntity allMenuEntity = new MenuEntity();
                            allMenuEntity.setId("all");
                            allMenuEntity.setTitle("更多");
                            indexDataList.add(allMenuEntity);
                            adapter.notifyDataSetChanged();


                        } else {
                            ToastUtil.error(getActivity(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    public void getAllNotifyCount() {
        OkHttpUtils
                .get(NewBaseUrl.getAllNotifyCount)
                .params("token", (String) SPUtils.get(getActivity(), "token", ""))
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "未处理工作数量: " + result);

                        com.alibaba.fastjson.JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getActivity());
                        if (code == 0) {

                            try {
                                tvWorkCount.setText(jsonObj.getString("toDoListCount"));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
//                            ToastUtil.error(getActivity(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();
        try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)    {       StatusBarCompat.setStatusBarColor(getActivity(), getResources().getColor(R.color.white), true);}
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }
        getSelect();
        getAllNotifyCount();
        initScan();
        try {
            IntentFilter filter = new IntentFilter();
            int[] idbuf = new int[]{PropertyID.WEDGE_INTENT_ACTION_NAME, PropertyID.WEDGE_INTENT_DATA_STRING_TAG};
            String[] value_buf = mScanManager.getParameterString(idbuf);
            if(value_buf != null && value_buf[0] != null && !value_buf[0].equals("")) {
                filter.addAction(value_buf[0]);
            } else {
                filter.addAction(SCAN_ACTION);
            }

            getActivity().registerReceiver(mScanReceiver, filter);
        } catch (Exception e) {
//            e.printStackTrace();
        }

//        MobclickAgent.onPageStart("操作页"); //统计页面，"MainScreen"为页面名称，可自定义


    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("操作页");
        try {
            if(mScanManager != null) {
                mScanManager.stopDecode();
            }
            getActivity(). unregisterReceiver(mScanReceiver);
        } catch (Exception e) {
//            e.printStackTrace();
        }

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 在使用这个view之前首先判断其是否存在parent view，这调用getParent()方法可以实现。
        // 如果存在parent view，那么就调用removeAllViewsInLayout()方法
        Log.i("test", "AFragment-->onCreateView");
        ViewGroup perentView = (ViewGroup) rootView.getParent();
        if (perentView != null) {
            perentView.removeAllViewsInLayout();
        }

        unbinder1 = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
//        unbinder.unbind();
        unbinder1.unbind();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == SCANNING_CODE && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(NewBaseUrl.DECODED_CONTENT_KEY);
                //Toast.makeText(getContext(), "扫描结果： " + content, Toast.LENGTH_SHORT).show();
                dealScan(content);

//                ToastUtil.makeText(getActivity(),content);


            }
        }
    }

    private void dealScan(String content) {
        Pattern pattern = Pattern.compile("\\s*/(device|user|terminal|beltline)/(\\d+)");
        Matcher matcher = pattern.matcher(content);
        if (matcher.find()) {
            switch (matcher.group(1)) {
                case "device":
                    Bundle bundle = new Bundle();
                    bundle.putString("id", matcher.group(2));
                    IntentUtils.startActivity(getActivity(), ScanDeviceEmptyActivity.class, bundle);

                    break;
                case "user":
                    bundle = new Bundle();
                    bundle.putString("id", matcher.group(2));
                    IntentUtils.startActivity(getActivity(), UserInfActivity.class, bundle);
                    break;
                case "terminal":
                    bundle = new Bundle();
                    bundle.putString("id", matcher.group(2));
                    IntentUtils.startActivity(getActivity(), TerminalInfActivity.class, bundle);
                    break;

                case "beltline":
                    bundle = new Bundle();
                    bundle.putString("id", matcher.group(2));
                    IntentUtils.startActivity(getActivity(), BeltlineInfActivity.class, bundle);
                    break;
            }


        } else {
            ToastUtil.makeText(getActivity(), "无效的二维码");

        }
    }

    // 判断是否开启相机权限
    private boolean checkPer() {
        if ((ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, 1002);
            return false;
        }
        return true;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1002:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //用户同意授权
                    Intent intent = new Intent(getActivity(), CustomCaptureActivity.class);
                    startActivityForResult(intent, SCANNING_CODE);
                } else {
                    //用户拒绝授权
                    ViewUtil.Dialog(getActivity());
                }
                break;
        }
    }


    private String getVersionName() throws Exception {
        // 获取packagemanager的实例
        PackageManager packageManager = getActivity().getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(getActivity().getPackageName(), 0);
        String version = packInfo.versionName;
        return version;
    }


    /*
       版本升级dialog
    */
    public void DelDialog() {
        final AlertDialog dialog = new AlertDialog.Builder(getContext()).create();
        dialog.show();
        dialog.getWindow().setContentView(R.layout.del_layouts);
        dialog.setCancelable(false);
        TextView mLine_Names = (TextView) dialog.findViewById(R.id.mLine_Names);
        mLine_Names.setText(contents);
        if (mustUpdate.equals("1")) {
            Button button = dialog.getWindow().findViewById(R.id.mNoDimsss);
            button.setText("退出");
        }

        dialog.getWindow().findViewById(R.id.mNoDimsss).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mustUpdate.equals("0")) {
                    dialog.dismiss();
                } else {
                    dialog.dismiss();
//                    IntentUtils.startActivity(getActivity(), LoginActivity.class);
                    getActivity().finish();

                }
            }
        });
        dialog.getWindow().findViewById(R.id.mDetermines).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File appDir = new File(getActivity().getFilesDir().getPath());

                ToastUtil.print(appDir.getAbsolutePath());
                if (!appDir.exists()) {
                    appDir.mkdir();
                }
                dialog.dismiss();
                VersionUpdateConfig.getInstance()//获取配置实例
                        .setContext(getActivity())//设置上下文
                        .setDownLoadURL(attachfile)//设置文件下载链接
                        .setNewVersion(version)//设置即将下载的APK的版本号,避免重复下载
//                         .setFileSavePath(appDir.getPath())//设置文件保存路径（可不设置）
                        .setNotificationIconRes(R.mipmap.baselogo)//设置通知图标
                        .setNotificationSmallIconRes(R.mipmap.baselogo)//设置通知小图标
                        .setNotificationTitle("陀曼智造(版本更新)")//设置通知标题
                        .startDownLoad();//开始下载
                Toast.makeText(getContext(), "开始下载...", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void newYearDialog() {
        final AlertDialog dialog = new AlertDialog.Builder(getContext()).create();
        dialog.show();
        dialog.getWindow().setContentView(R.layout.dialog_newyear);
        dialog.setCancelable(false);
        ImageView iv_photo = (ImageView) dialog.findViewById(R.id.iv_photo);
        ImageView iv_close = (ImageView) dialog.findViewById(R.id.iv_close);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);


        dialog.getWindow().findViewById(R.id.iv_photo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                dialog.dismiss();


            }
        });
        dialog.getWindow().findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    /*
     升级app
   */
    public void appUpdata() {
        OkHttpUtils
                .get(NewBaseUrl.app_update)
                .params("platform","1")
                .params("token", (String) SPUtils.get(getActivity(), "token", ""))
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        try {
                            JSONObject js = new JSONObject(result);
                            int code = js.getInt("code");
                            ViewUtil.lagout(code, getActivity());
                            if (code == 0) {
                                JSONObject data = js.getJSONObject("data");
                                Log.i("test", "版本更新： " + data.toString());

                                contents = data.getString("content");
                                version = data.getString("version");
                                attachfile = data.getString("attachfile");
                                try {
                                    mustUpdate = data.getString("mustUpdate");
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                if (version.equals(getVersionName())) {
//                                     Toast.makeText(getContext(), "当前已是最新版本!", Toast.LENGTH_SHORT).show();

//                                    DelDialog();
                                } else {
                                    Log.i("test", "执行了: ");
                                    DelDialog();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    public void updateDiy( ) {

//        String path = Environment.getExternalStorageDirectory().getAbsolutePath();

        Map<String, String> params = new HashMap<String, String>();

//        params.put("appKey", "ab55ce55Ac4bcP408cPb8c1Aaeac179c5f6f");
//        params.put("appVersion", AppUpdateUtils.getVersionName(getActivity()));
        params.put("platform", "1");
        params.put("token", (String) SPUtils.get(getActivity(), "token", ""));


        new UpdateAppManager
                .Builder()
                //必须设置，当前Activity
                .setActivity(getActivity())
                //必须设置，实现httpManager接口的对象
                .setHttpManager(new UpdateAppHttpUtil())
                //必须设置，更新地址
                .setUpdateUrl(NewBaseUrl.app_update)
                //全局异常捕获
                .handleException(new ExceptionHandler() {
                    @Override
                    public void onException(Exception e) {
                        e.printStackTrace();
                    }
                })
                //以下设置，都是可选
                //设置请求方式，默认get
                .setPost(false)
                //不显示通知栏进度条
//                .dismissNotificationProgress()
                //是否忽略版本
//                .showIgnoreVersion()
                //添加自定义参数，默认version=1.0.0（app的versionName）；apkKey=唯一表示（在AndroidManifest.xml配置）
                .setParams(params)
                //设置点击升级后，消失对话框，默认点击升级后，对话框显示下载进度，如果是强制更新，则设置无效
//                .hideDialogOnDownloading()
                //设置头部，不设置显示默认的图片，设置图片后自动识别主色调，然后为按钮，进度条设置颜色
                .setTopPic(R.mipmap.top_8)
                //为按钮，进度条设置颜色。
                .setThemeColor(0xffffac5d)
                //设置apk下砸路径，默认是在下载到sd卡下/Download/1.0.0/test.apk
//                .setTargetPath(path)
                //设置appKey，默认从AndroidManifest.xml获取，如果，使用自定义参数，则此项无效
//                .setAppKey("ab55ce55Ac4bcP408cPb8c1Aaeac179c5f6f")
                .setUpdateDialogFragmentListener(new IUpdateDialogFragmentListener() {
                    @Override
                    public void onUpdateNotifyDialogCancel(UpdateAppBean updateApp) {
                        //用户点击关闭按钮，取消了更新，如果是下载完，用户取消了安装，则可以在 onActivityResult 监听到。

                    }
                })
                //不自动，获取
//                .setIgnoreDefParams(true)
                .build()
                //检测是否有新版本
                .checkNewApp(new UpdateCallback() {
                    /**
                     * 解析json,自定义协议
                     *
                     * @param json 服务器返回的json
                     * @return UpdateAppBean
                     */
                    @Override
                    protected UpdateAppBean parseJson(String json) {
                        UpdateAppBean updateAppBean = new UpdateAppBean();
                        ToastUtil.error(getActivity(),json);
                        try {
                            JSONObject jsonObject = new JSONObject(json);
                            String update="No";
                            if (jsonObject.optString("update").equals("1")){
                                update="Yes";
                            }
                            updateAppBean
                                    //（必须）是否更新Yes,No
                                    .setUpdate(jsonObject.optString(update))
                                    //（必须）新版本号，
                                    .setNewVersion(jsonObject.optString("version"))
                                    //（必须）下载地址
                                    .setApkFileUrl(jsonObject.optString("attachfile"))
                                    //测试下载路径是重定向路径
//                                    .setApkFileUrl("http://openbox.mobilem.360.cn/index/d/sid/3282847")
//                                    .setUpdateDefDialogTitle(String.format("AppUpdate 是否升级到%s版本？", newVersion))
                                    //（必须）更新内容
                                    .setUpdateLog(jsonObject.optString("content"))
                                    //测试内容过度
//                                    .setUpdateLog("测试")
//                                    .setUpdateLog("1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16")
//                                    .setUpdateLog("今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说相对于其他行业来说今天我们来聊一聊程序员枯燥的编程生活，相对于其他行业来说\r\n")
                                    //大小，不设置不显示大小，可以不设置
//                                    .setTargetSize(jsonObject.optString("target_size"))
                                    //是否强制更新，可以不设置
                                    .setConstraint(true);
                                    //设置md5，可以不设置
//                                    .setNewMd5(jsonObject.optString("new_md5"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        return updateAppBean;
                    }

                    @Override
                    protected void hasNewApp(UpdateAppBean updateApp, UpdateAppManager updateAppManager) {
                        updateAppManager.showDialogFragment();
                    }

                    /**
                     * 网络请求之前
                     */
                    @Override
                    public void onBefore() {
                        CProgressDialogUtils.showProgressDialog(getActivity());
                    }

                    /**
                     * 网路请求之后
                     */
                    @Override
                    public void onAfter() {
                        CProgressDialogUtils.cancelProgressDialog(getActivity());
                    }

                    /**
                     * 没有新版本
                     */
                    @Override
                    public void noNewApp(String error) {
                        Toast.makeText(getActivity(), "没有新版本", Toast.LENGTH_SHORT).show();
                    }
                });

    }



    public void logSave(String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("menuId",id);
        OkHttpUtils
                .post(NewBaseUrl.log_save)
                .headers("token", (String) SPUtils.get(getActivity(), "token", ""))
                .postJson(JsonUtils.obj2JsonString(map))
                        .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {

                    }
                });
    }

    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            soundpool.play(soundid, 1, 1, 0, 0, 1);
            mVibrator.vibrate(100);

            byte[] barcode = intent.getByteArrayExtra(ScanManager.DECODE_DATA_TAG);
            int barcodelen = intent.getIntExtra(ScanManager.BARCODE_LENGTH_TAG, 0);
            byte temp = intent.getByteExtra(ScanManager.BARCODE_TYPE_TAG, (byte) 0);
            android.util.Log.i("debug", "----codetype--" + temp);
            barcodeStr = new String(barcode, 0, barcodelen);
        dealScan(barcodeStr);
        }
    };

    @OnClick({R.id.iv_scan, R.id.cv_work})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_scan:
                if (checkPer()) {
                    Intent intent = new Intent(getActivity(), CustomCaptureActivity.class);
                    startActivityForResult(intent, SCANNING_CODE);
                }
                break;
            case R.id.cv_work:
                IntentUtils.startActivity(getActivity(), MsgUnReadActivity.class);
//                IntentUtils.startActivity(getActivity(), ProblemFeedbackActivity.class);
                break;
        }
    }
}
